package com.gyh.system.sys.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gyh.system.sys.entity.User;
import com.gyh.system.sys.service.PermissionService;
import com.gyh.system.sys.service.UserService;

public class MyRealm extends AuthorizingRealm{
	
	private static final Logger log = LoggerFactory.getLogger(MyRealm.class);

	@Resource
	private UserService userService;
	
	@Resource
	private PermissionService permissionService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//		authorizationInfo.setRoles(userService.gainUserOfRole(userName));
//		authorizationInfo.setStringPermissions(permissionService.gainPermissionUrls(userName));
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		log.info(userName+"用户，正在进行验证");
		User user = userService.get(new User(userName));
		if (user == null) {
			throw new UnknownAccountException("用户名不存在");
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(token.getCredentials(), user.getPassword(),"myRealm");
		return authenticationInfo;
	}

}
